import Compressor from 'compressorjs';
import {uploaderUrl,tiaozhuanUrl} from './urlconfig';

function yasuopic(file,filelist){

    if(file.size > 2000000){

        new Compressor(file, {
            quality: 0.6,

            success(result) {
                filelist.push(result);
                console.log(result.size);

            },
            error(err) {
                console.log(err.message);
                filelist.push("");

            },
        });
    }else{
        console.log("no yasuo");
        console.log(file.size);
        filelist.push(file);

    }


}


// var formData = new FormData();
// var filelist = [];
// var statusindex = 0;

// document.getElementById('file').addEventListener('change', (e) => {
//     const file = e.target.files[0];
  
//     if (!file) {
//       return;
//     }

//     statusindex = yasuopic(file,filelist,statusindex);
//     console.log(statusindex);

// });




var filelist = [];
var totalpicnum = 0;
var maxpicnum = 9;
var select_index_dom = null;  // 删除的index dom
var file_index = 0; //图片的实际index
$(function(){
    var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',
        $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
        $uploaderInput = $("#uploaderInput"),
        $uploaderFiles = $("#uploaderFiles"),
        $weuitextarea = $("#weuitextarea"),
        $delthisimg = $("#delthisimg")
        ;
    $weuitextarea.on("input", function(e){
        // 更新图文字数量
        var totaltxtnum = $weuitextarea.val().length;
        $("#weuitextareanum").text(totaltxtnum);            
    });
    $uploaderInput.on("change", function(e){
        if(totalpicnum >= maxpicnum){
            document.querySelector("#iosDialog2 > div.weui-dialog > div.weui-dialog__bd").textContent = "最多只能九张图片";
            $("#iosDialog2").show();
            return;
        } 

        var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
        
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];

            if (url) {
                src = url.createObjectURL(file);
            } else {
                src = e.target.result;
            }

             
            var $picdom = $(tmpl.replace('#url#', src)).data("index",file_index);
            $uploaderFiles.append($picdom);
            // 压缩图片
            yasuopic(file,filelist);

            file_index += 1;
        }

        uptotalpicnum();

        // 清空value 这样可以重复选择一张图片
        $uploaderInput.val("");

    });
    $uploaderFiles.on("click", "li", function(){
        // 设置选择的index
        select_index_dom = this;
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.show();
        $gallery.removeClass("weui-animate-fade-out").addClass("weui-animate-fade-in");
    });
    $gallery.on("click", function(){
        $gallery.hide();
        $gallery.removeClass("weui-animate-fade-in").addClass("weui-animate-fade-out");
    });
    $delthisimg.on("click", function(){
        if(select_index_dom){
            // 删除上传列表里面的数据 还有删除dom
            var select_index = $(select_index_dom).data("index");
            delete filelist[select_index]; // delete 并不会影响filelist的length
            
            $(select_index_dom).remove();
            uptotalpicnum();
        }
    });
    var $zhidaole = $("#iosDialog2");
    $zhidaole.on("click", function(){
        $zhidaole.hide();
    });
});

window.uptotalpicnum = function (){
        // 更新图片数量
        totalpicnum = $("#uploaderFiles").children().length;
        $("#picnum").text(totalpicnum);
};


var clickbool = false; //只给用户点击一次的机会
// 要干的事情，禁用按钮，避免反复按 初步验证输入的数据 根据异常情况给与提示 构建发送的数据 根据返回情况给与提示 或者跳转
window.fapengyouquan = function (that,num){
    if(clickbool){
        return ;
    }else{
        clickbool = true;
        $(that).css("background-color","#ffffff");
    }
    

    var saytext = $("#weuitextarea").val();
    var errortext = "";


    if(totalpicnum != maxpicnum){

        if(totalpicnum == 0 && saytext == ""){ //没有图片也没有话的情况
            errortext = "没有编辑内容";
        }

        if(totalpicnum > maxpicnum){
            errortext += "图片太多了";
            
        }

        if(saytext.length > 200){
            errortext += "文字太长了";
        }

        if (/^[\u4e00-\u9fa5A-Za-z：，。？！:,.?!\n\s]{0,200}$/.test(saytext)) {
            // Successful match
        } else {
            errortext += "请输入一些简单的话，不要包括其他符号";
        }

        var realnum = 0;
        for (var i = 0, len = filelist.length; i < len; ++i) {
            if(filelist[i]){
                realnum += 1;
            }
        }

        if(totalpicnum != realnum){
            errortext += "系统繁忙或者出错，请稍后"; // 这里是预防图片没有压缩完就点发朋友圈,因为压缩是异步的，但这个测试起来比较难
        }
    }


    

    if(errortext){
        // 恢复按钮的状态
        clickbool = false;
        $(that).css("background-color","#cccccc");
        showerror(errortext);
        return;
    }

    // 显示loading
    var $loadingToast = $("#loadingToast");
    $loadingToast.show();
    var formData = new FormData();


    for (var i = 0, len = filelist.length; i < len; ++i) {
        if(filelist[i]){
            formData.append('Files[]', filelist[i], filelist[i].name);
        }
    }
    
    formData.append('saysomething', saytext);

    $.ajax({
        url: uploaderUrl,
        type: "POST",
        data: formData,
        contentType: false, //必须false才会自动加上正确的Content-Type
        processData: false, //必须false才会避开jQuery对 formdata 的默认处理
        success: function(res) {
            window.location.href = tiaozhuanUrl;
        },
        error: function(oEvent) {
            // 隐藏loading
            $loadingToast.hide();

            errortext = "服务器有问题";
            showerror(errortext);
            console.log("ok");
        }
    });

};


window.showerror = function (errortext){
    var $iosDialog2 = $("#iosDialog2");
    document.querySelector("#iosDialog2 > div.weui-dialog > div.weui-dialog__bd").textContent = errortext;
    $iosDialog2.show();
};